package com.xiaoxu.intranetweb.mybatisplusSzappdb.business.sampling;

import cn.dev33.satoken.stp.StpUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sun.org.apache.bcel.internal.generic.NEW;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.dao.UserInfoDao;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.entity.*;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.mapper.CWeightPicturesSamplingMapper;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.service.*;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.vo.GetSamplingImgAndDetailVo;
import com.xiaoxu.intranetweb.util.SzResult;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

@Component
@Slf4j
public class SamplingBu {
    @Autowired
    private ITSamplingRecordService samplingRecordService;
    @Autowired
    private ITCoalYardAreaService coalYardAreaService;
    @Autowired
    private UserInfoDao userInfoDao;
    @Autowired
    private ICProductsInfoService cProductsInfoService;
    @Autowired
    private ICCompanysService cCompanysService;
    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private CWeightPicturesSamplingMapper cWeightPicturesSamplingMapper;
    @Autowired
    private ICWeightSheetsService cWeightSheetsService;
    @Autowired
    private ICAshGateVideoBindService cAshGateVideoBindService;
//    入厂确认
    public SzResult enterConfirm(  String coalYardAreaId, String weightSheetNo,  String userId, String enterTime) {
        LocalDateTime now = LocalDateTime.now();

        if (enterTime != null && !enterTime.isEmpty()) {
            // 自定义日期时间格式
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            try {
                now = LocalDateTime.parse(enterTime, formatter);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        try {
//            SysUser sysUser =userInfoDao.getUser(StpUtil.getLoginIdByToken(token).toString());
            QueryWrapper<TSamplingRecord> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("WEIGHT_SHEET_NO",weightSheetNo);
            TSamplingRecord tSamplingRecord1 = samplingRecordService.getOne(queryWrapper);
            if (tSamplingRecord1 != null) {
                TCoalYardArea coalYardArea =   coalYardAreaService.getById(coalYardAreaId);
                TSamplingRecord tSamplingRecord = new TSamplingRecord();
                tSamplingRecord.setId(tSamplingRecord1.getId());
                tSamplingRecord.setAshgateId(coalYardArea.getAshGateId());
                tSamplingRecord.setWeightSheetNo(weightSheetNo);
                tSamplingRecord.setCoalYardAreaId(coalYardArea.getId());
                tSamplingRecord.setEnterTime(now);
                tSamplingRecord.setEnterUserId(userId);
                samplingRecordService.updateById(tSamplingRecord);
            }else {
                TCoalYardArea coalYardArea = coalYardAreaService.getById(coalYardAreaId);
                TSamplingRecord tSamplingRecord = new TSamplingRecord();
                tSamplingRecord.setAshgateId(coalYardArea.getAshGateId());
                tSamplingRecord.setWeightSheetNo(weightSheetNo);
                tSamplingRecord.setCoalYardAreaId(coalYardArea.getId());
                tSamplingRecord.setEnterTime(now);
                tSamplingRecord.setEnterUserId(userId);
                samplingRecordService.save(tSamplingRecord);
            }
        return SzResult.Success();
        }catch (Exception e) {
            return SzResult.Error("服务出错，用户信息错误");
        }
    }
//    //    出厂确认
    public SzResult outConfirm( String weightSheetNo,String userId,String outTime) {
        LocalDateTime now = LocalDateTime.now();

        if (outTime != null && !outTime.isEmpty()) {
            // 自定义日期时间格式
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            try {
                now = LocalDateTime.parse(outTime, formatter);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        try {
            QueryWrapper<TSamplingRecord> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("WEIGHT_SHEET_NO",weightSheetNo);
            TSamplingRecord tSamplingRecord1 = samplingRecordService.getOne(queryWrapper);
            if (tSamplingRecord1 != null) {
                TSamplingRecord tSamplingRecord = new TSamplingRecord();
                tSamplingRecord.setId(tSamplingRecord1.getId());
                tSamplingRecord.setWeightSheetNo(weightSheetNo);
                tSamplingRecord.setOutTime(now);
                tSamplingRecord.setOutUserId(userId);
                samplingRecordService.updateById(tSamplingRecord);
                return SzResult.Success();
            }else {
                TSamplingRecord tSamplingRecord = new TSamplingRecord();
                tSamplingRecord.setWeightSheetNo(weightSheetNo);
                tSamplingRecord.setOutTime(now);
                tSamplingRecord.setOutUserId(userId);
                samplingRecordService.save(tSamplingRecord);
                return SzResult.Success();
            }
        }catch (Exception e) {
            return SzResult.Error("服务出错，用户信息错误");
        }
    }
//    卸车确认
    public SzResult unloadConfirm(String weightSheetNo,String sampWght) {
        LocalDateTime now = LocalDateTime.now();
        try {
            QueryWrapper<TSamplingRecord> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("WEIGHT_SHEET_NO",weightSheetNo);
            TSamplingRecord tSamplingRecord1 = samplingRecordService.getOne(queryWrapper);
            if (tSamplingRecord1 != null) {
                TSamplingRecord tSamplingRecord = new TSamplingRecord();
                tSamplingRecord.setId(tSamplingRecord1.getId());
                tSamplingRecord.setWeightSheetNo(weightSheetNo);
                if (sampWght != null) {
                    tSamplingRecord.setSampWght(new BigDecimal(sampWght));
                }
                samplingRecordService.updateById(tSamplingRecord);
                return SzResult.Success();
            }else {
                TSamplingRecord tSamplingRecord = new TSamplingRecord();
                tSamplingRecord.setWeightSheetNo(weightSheetNo);
                tSamplingRecord.setUnloadTime(now);
                if (sampWght != null) {
                    tSamplingRecord.setSampWght(new BigDecimal(sampWght));
                }
                samplingRecordService.save(tSamplingRecord);
            }
            return SzResult.Success();
        }catch (Exception e) {
            return SzResult.Error("服务出错，用户信息错误");
        }
    }
//    根据单子的id查到采样记录
    public SzResult getEnterConfirm(String token , String weightSheetNo) {
        try {
            QueryWrapper<TSamplingRecord> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("WEIGHT_SHEET_NO",weightSheetNo);
            TSamplingRecord tSamplingRecord = samplingRecordService.getOne(queryWrapper);
            return SzResult.success(tSamplingRecord);
        }catch (Exception e) {
            return SzResult.Error("服务出错，用户信息错误");
        }
    }
//    获取品种、单位信息
    public SzResult getUserAndCpyAndPdt( ) {
        try {
          QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("DEL_FLAG", 0);
          List<SysUser> userList =   sysUserService.list(queryWrapper);
          QueryWrapper<CCompanys> queryWrapper1 = new QueryWrapper<>();
          queryWrapper1.eq("CPY_DELETED", 0);
          List<CCompanys> cCompanysList =   cCompanysService.list(queryWrapper1);
          QueryWrapper<CProductsInfo> queryWrapper2 = new QueryWrapper<>();
          queryWrapper2.eq("PDTINF_DELETED", 0);
          List<CProductsInfo> cProductsInfoList =   cProductsInfoService.list(queryWrapper2);
            Map<String, Object> map = new HashMap<>();
            map.put("userList",userList);
            map.put("cCompanysList",cCompanysList);
            map.put("cProductsInfoList",cProductsInfoList);
            map.put("coalYardAreaList",coalYardAreaService.getAllList());
            return SzResult.success(map);
        }catch (Exception e) {
            return SzResult.Error("服务出错，用户信息错误");
       }
    }
//getSamplingImgAndDetail
    public SzResult getSamplingImgAndDetail(String weipicSheetno) {
        try {
            GetSamplingImgAndDetailVo getSamplingImgAndDetailVo = new GetSamplingImgAndDetailVo();
            QueryWrapper<CWeightSheets> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("WEISHT_SHEETNO",weipicSheetno);
            CWeightSheets cWeightSheets = cWeightSheetsService.getOne(queryWrapper);
            if (cWeightSheets != null){
                if (cWeightSheets.getWeishtSampCode() == null){
                    return SzResult.Error("此单无采样数据");
                }
            }
//            采样区域
            if (cWeightSheets != null && cWeightSheets.getWeishtSampAreas() != null) {
                getSamplingImgAndDetailVo.setWeishtSampAreas(cWeightSheets.getWeishtSampAreas());
            }
//            采样编码
            if (cWeightSheets != null) {
                getSamplingImgAndDetailVo.setWeishtSampCode(cWeightSheets.getWeishtSampCode());
            }
//采样方案
            if (cWeightSheets != null) {
                getSamplingImgAndDetailVo.setWeishtSampScheme(cWeightSheets.getWeishtSampScheme());
            }
//            入厂确认人
            if (cWeightSheets != null) {
                getSamplingImgAndDetailVo.setWeishtAffirmMan(cWeightSheets.getWeishtAffirmMan());
            }
//            入厂确认时间
            if (cWeightSheets != null) {
                getSamplingImgAndDetailVo.setWeishtAffirmTm(String.valueOf(cWeightSheets.getWeishtAffirmTm()));
            }
//            出厂确认人
            if (cWeightSheets != null) {
                getSamplingImgAndDetailVo.setWeishtAffirmMan2(cWeightSheets.getWeishtAffirmMan2());
            }
//            出厂确认时间
            if (cWeightSheets != null) {
                getSamplingImgAndDetailVo.setWeishtAffirmTm2(String.valueOf(cWeightSheets.getWeishtAffirmTm2()));
            }
//            单号
            if (cWeightSheets != null) {
                getSamplingImgAndDetailVo.setWeipicSheetno(cWeightSheets.getWeishtSheetno());
            }
//            管控id
            if (cWeightSheets != null) {
                getSamplingImgAndDetailVo.setWeishtMgtCtrlId(cWeightSheets.getWeishtMgtCtrlId());
            }
//            调运单号
            if (cWeightSheets != null) {
                getSamplingImgAndDetailVo.setWeishtDispatchNo(cWeightSheets.getWeishtDispatchNo());
            }
//            采样区域
            if (cWeightSheets != null && cWeightSheets.getWeishtSampAreas() != null) {
                QueryWrapper<TCoalYardArea> queryWrapper1 = new QueryWrapper<>();
                queryWrapper1.eq("ID", cWeightSheets.getWeishtAffirmAreaId());
                TCoalYardArea tCoalYardArea = coalYardAreaService.getOne(queryWrapper1);
                QueryWrapper<CAshGateVideoBind> queryWrapper2 = new QueryWrapper<>();
                queryWrapper2.eq("ID", tCoalYardArea.getAshGateId());
                CAshGateVideoBind cAshGateVideoBind = cAshGateVideoBindService.getOne(queryWrapper2);
                getSamplingImgAndDetailVo.setWeishtSampAreasName(cAshGateVideoBind.getAshgateName() + "【" + tCoalYardArea.getAshGateArea() + "】");
            }
            CWeightPicturesSampling cWeightPicturesSampling = cWeightPicturesSamplingMapper.selectBySheetNo(weipicSheetno);
            if (cWeightPicturesSampling != null) {
                // 使用 setFixedImage 方法来修复并设置图片字段
                setFixedImage(cWeightPicturesSampling.getWeipicSamp1(), getSamplingImgAndDetailVo::setWeipicSamp1);
                setFixedImage(cWeightPicturesSampling.getWeipicSamp2(), getSamplingImgAndDetailVo::setWeipicSamp2);
                setFixedImage(cWeightPicturesSampling.getWeipicSamp3(), getSamplingImgAndDetailVo::setWeipicSamp3);
                setFixedImage(cWeightPicturesSampling.getWeipicSamp4(), getSamplingImgAndDetailVo::setWeipicSamp4);
                setFixedImage(cWeightPicturesSampling.getWeipicSamp5(), getSamplingImgAndDetailVo::setWeipicSamp5);
                setFixedImage(cWeightPicturesSampling.getWeipicSamp6(), getSamplingImgAndDetailVo::setWeipicSamp6);
                setFixedImage(cWeightPicturesSampling.getWeipicSamp7(), getSamplingImgAndDetailVo::setWeipicSamp7);
                setFixedImage(cWeightPicturesSampling.getWeipicSamp8(), getSamplingImgAndDetailVo::setWeipicSamp8);
                setFixedImage(cWeightPicturesSampling.getWeipicSamp9(), getSamplingImgAndDetailVo::setWeipicSamp9);
                setFixedImage(cWeightPicturesSampling.getWeipicSamp10(), getSamplingImgAndDetailVo::setWeipicSamp10);
            }
            QueryWrapper<TSamplingRecord> queryWrapper2 = new QueryWrapper<>();
            queryWrapper2.eq("WEIGHT_SHEET_NO",weipicSheetno);
            TSamplingRecord tSamplingRecord = samplingRecordService.getOne(queryWrapper2);
            if (tSamplingRecord != null) {
                getSamplingImgAndDetailVo.setWeishtSampWght(tSamplingRecord.getSampWght());
            }
            return SzResult.success(getSamplingImgAndDetailVo);
        }catch (Exception e){
            return SzResult.Error("服务出错"+e.getMessage());
        }
    }
    private void setFixedImage(byte[] imageData, java.util.function.Consumer<String> setter) {
        if (imageData == null || imageData.length == 0) {
            return;
        }

        try {
            String base64String = Base64.getEncoder().encodeToString(imageData);

            // 检查并提取不同图片格式的纯Base64数据
            String pureBase64 = extractPureBase64(base64String);
            setter.accept(pureBase64);

        } catch (Exception e) {
            log.warn("转换图片失败: " + e.getMessage());
        }
    }

    private String extractPureBase64(String base64String) {
        // JPEG格式: 以"/9j/"开头
        int jpegStart = base64String.indexOf("/9j/");
        if (jpegStart != -1) {
            return base64String.substring(jpegStart);
        }

        // PNG格式: 以"iVBORw0KGgo"开头
        int pngStart = base64String.indexOf("iVBORw0KGgo");
        if (pngStart != -1) {
            return base64String.substring(pngStart);
        }

        // GIF格式: 以"R0lGOD"开头
        int gifStart = base64String.indexOf("R0lGOD");
        if (gifStart != -1) {
            return base64String.substring(gifStart);
        }

        // 如果都不是已知格式，返回完整的Base64
        return base64String;
    }
//    查询批次的所有采样重量
    public SzResult getBatchAllSamplingWeight(String weightSheetNo) {
        JSONObject jsonObject = new JSONObject();
        QueryWrapper<CWeightSheets> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("WEISHT_SHEETNO",weightSheetNo);
        queryWrapper.eq("WEISHT_DELETED",0);
        CWeightSheets cWeightSheets = cWeightSheetsService.getOne(queryWrapper);
//        拿到批次号
        String weishtBatch = cWeightSheets.getWeishtBatch();
//        根据批次号查询所有，同一批次的磅单单号
        QueryWrapper<CWeightSheets> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("WEISHT_BATCH",weishtBatch);
        queryWrapper1.eq("WEISHT_DELETED",0);
        List<CWeightSheets> list = cWeightSheetsService.list(queryWrapper1);
        List<String> list1 = new ArrayList<>();
        int sampAreasCount = 0;
        BigDecimal weishtNetWght = new BigDecimal(0);
        for (CWeightSheets cWeightSheets1 : list) {
            list1.add(cWeightSheets1.getWeishtSheetno());
//            //            这里有个采样点字段，数据是1,2,3像这样就是3个点，采样点字段为空就是没有采样点，所以我要计算出一共有多少个采样点
            if (cWeightSheets1.getWeishtSampAreas() != null) {
                sampAreasCount =sampAreasCount + cWeightSheets1.getWeishtSampAreas().split(",").length;
                jsonObject.put("sampAreasCount",sampAreasCount);
            }
            if (cWeightSheets1.getWeishtNetWght() != null) {
                weishtNetWght =weishtNetWght.add(cWeightSheets1.getWeishtNetWght());
                jsonObject.put("weishtNetWght",weishtNetWght);
            }
        }
        QueryWrapper<TSamplingRecord> queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.in("WEIGHT_SHEET_NO",list1);
        List<TSamplingRecord> tSamplingRecord = samplingRecordService.list(queryWrapper2);

        if (tSamplingRecord != null && !tSamplingRecord.isEmpty()) {
            List<BigDecimal> sampWghtList = tSamplingRecord.stream()
                    .map(TSamplingRecord::getSampWght)
                    .filter(Objects::nonNull) // 过滤掉 null 值
                    .collect(Collectors.toList());

            BigDecimal sum = sampWghtList.stream()
                    .reduce(BigDecimal::add)
                    .orElse(BigDecimal.ZERO);

            jsonObject.put("sampWght", sum);
        } else {
            jsonObject.put("sampWght", BigDecimal.ZERO);
        }
        return SzResult.success(jsonObject);
    }


}
